#include "main.h"

static gchar comb_tmp_out[5];
static gchar comb_tmp_used[5] = {0};
 

/* 
 * ===  FUNCTION  ======================================================================
 *         Name:  comb
 *  Description:  combine algrithm
 * =====================================================================================
 */
void _comb(const gchar *str, gint n, gint r, gint pos, gint h, GString *expr)
{
  gint i;

  // if already choose number of r chars, return
  if (pos == r) {
    for (i = 0; i < r; i++) {
      g_string_append_c (expr, comb_tmp_out[i]);
    }
    g_string_append_c (expr, ' ');
    return;
  }

  for (i = h; i <= n - r + pos; i++)
    // for all unused element
    if (!comb_tmp_used[i]) {
      // put it in the combination array
      comb_tmp_out[pos] = str[i];
      // mark as used
      comb_tmp_used[i]++;
      // search i+1 element
      _comb(str, n, r, pos+1, i+1, expr);
      // restore as unused
      comb_tmp_used[i]--;
  }
}


/* 
 * ===  FUNCTION  ======================================================================
 *         Name:  parse_angle_get_comb_str
 *  Description:  
 * =====================================================================================
 */
GString *parse_angle_get_comb_str (GString *str)
{
  gint i;
  GString *expr = g_string_new (NULL);

  for (i = 0; i <= str->len; i++) {
    _comb (str->str, str->len, i, 0, 0, expr);
  }

  // strip space
  gchar *tmp = g_strdup (expr->str);
  g_strstrip (tmp);
  g_string_erase (expr, 0, -1);
  g_string_append (expr, tmp);

  g_free (tmp);

  g_debug ("(%s)\n", expr->str);

  return expr;
}



/* 
 * ===  FUNCTION  ======================================================================
 *         Name:  parse_angle_comb_to_list
 *  Description:  
 * =====================================================================================
 */
GSList *parse_angle_comb_to_list (GString *expr)
{
  gint i = 0;
  GSList *head = NULL;

  // split by space
  gchar **str = g_strsplit (expr->str, " ", 0);

  while (str[i]) {
    GString *leaf = g_string_new (str[i]);
    g_debug ("str = %s", leaf->str);
    head = g_slist_append (head, leaf);
    i++;
  }

  g_strfreev (str);
  return head;

}
